package zhieasy.cn.xpu_helper.controller.common;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Api(tags = "common模块，图片操作接口")
@Slf4j
@RestController
@RequestMapping("/common/image")
public class CodeImageController {
    private static final String tmpDir = System.getProperty("java.io.tmpdir");

    @ApiOperation(value = "下载图片", notes = "输入图片名称即可", httpMethod = "GET")
    @GetMapping(value = "/download/{name}")
    public void downloadImage(@PathVariable("name") String name, HttpServletResponse response){
        try (OutputStream os = response.getOutputStream()){
            BufferedImage image = ImageIO.read(new FileInputStream(new File(tmpDir, name)));
            BufferedImage newImg= new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            newImg.getGraphics().drawImage(image, 0, 0, null);
            response.setContentType("image/jpg");
            ImageIO.write(newImg, "jpg", os);
        } catch (IOException e) {
            log.error("Download Images Error!", e);
        }
    }
}
